package org.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.netty.handler.ServerChannleInitializer;

public class NettyServerBootstrap {

    private int port;

    public NettyServerBootstrap(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        NettyServerBootstrap nettyServerBootstrap = new NettyServerBootstrap(10111);
        nettyServerBootstrap.run();
    }


    private void run() {
        EventLoopGroup boss = new NioEventLoopGroup();

        EventLoopGroup worker = new NioEventLoopGroup();

        ServerBootstrap server = new ServerBootstrap();

        server.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                //配置 NioServerSocketChannel 的 tcp 参数, BACKLOG 的大小
                .option(ChannelOption.SO_BACKLOG, 1024)
                .option(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ServerChannleInitializer());


        ChannelFuture channelFuture = null;
        try {
            channelFuture = server.bind(port).sync();
            if (channelFuture.isSuccess()) {
                System.out.println("server started");
            }
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
